'use strict';

const Controller = require('egg').Controller;

class CollectController extends Controller {
    async index() {
        const { ctx } = this;
        console.log(ctx.request.body);
        var { id, collected } = ctx.request.body //获取传来的参数 id和collected
        collected = (collected == "true") ? true : false //当collected 传过来 如果 == true 则为true 否则为false
        // console.log(collected);
        const db = this.app.mongodb
        await ctx.service.movie.getMovieCollect({ id, collected })
        const res = await ctx.service.movie.getMovieDetailOrSearch({ id: id });
        var item = res[0]
        console.log(res);
        try {
            if(collected){
              await db.collection("user").insertOne(item);
              ctx.body = {
                status:200,
                msg:"收藏成功"
              }
            }else{
              await db.collection("user").deleteOne({_id:(id)});
              ctx.body= {
                status:200,
                msg:"取消收藏"
              }
            }
            
            
          } catch (err) {
            this.app.logger.error(err);
            ctx.body = {
              status:400,
              msg:"数据库中数据已经存在,请不要重复添加"
            }
          }
    }
}

module.exports = CollectController;
